package com.itcodai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itcodai.dao.user.UserMapper;
import com.itcodai.utils.thread.RunGroupCallable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author c-fanqj
 * @date 2023/5/17
 * @apiNote
 */
@Service
public class TestService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserMapper userMapper;

    public List<String> test(JSONObject object) {
        List<JSONObject> verifyToolList = new ArrayList<>();
        long userId1 = object.getLong("userId1");
        long userId2 = object.getLong("userId2");
        JSONObject object1 = new JSONObject();
        object1.put("id", userId1);
        verifyToolList.add(object1);
        object1 = new JSONObject();
        object1.put("id", userId2);
        verifyToolList.add(object1);
        int poolNum = verifyToolList.size();
        poolNum = poolNum == 0 ? 10 : poolNum;
        ArrayList<String> messageList = new ArrayList<>();
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(poolNum);
            List<Future<String>> futures = new ArrayList<>();
            for (JSONObject verifyTool : verifyToolList) {
                futures.add(executorService.submit(new RunGroupCallable(verifyTool, userMapper)));
            }
            for (Future<String> future : futures) {
                String result = future.get(100, TimeUnit.SECONDS);
                logger.info("接收信息-{}", result);
                messageList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageList;
    }

    //@Override
    @Async("jmeterServiceExecutor")
    public void jmeterExecuteAsync(int index) {
        logger.info("start executeAsync3 task-{}", index);
        logger.info("threadName3-{}", Thread.currentThread().getName());
        try {
            Thread.sleep(50*1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        logger.info("end executeAsync2 task-{}", index);
    }

}
